#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
char * get_local_ip(char *interface)
{
    int fd, intrface, retn = 0;
    struct ifreq buf[INET_ADDRSTRLEN];
    struct ifconf ifc;
    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
    {
        ifc.ifc_len = sizeof(buf);
        // caddr_t,Linux内核源码里定义的：typedef void *caddr_t；
        ifc.ifc_buf = (caddr_t)buf;
        if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))
        {
                intrface = ifc.ifc_len/sizeof(struct ifreq);
                while (intrface-- > 0)
                {
                    if (!(ioctl(fd, SIOCGIFADDR, (char *)&buf[intrface])))
                    {
                        if (strcmp(interface, buf[intrface].ifr_name) == 0) {
                            return inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr);
                        }
                    }
                }
        }
        close(fd);
   }
   return "";
}


int main()
{
        char * p = get_local_ip("enp2s0");
        printf("%s\n",p);
        return 0;
}
